package com.example.cheapshark.mobile;

import android.os.Bundle;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;

public class TopDealsFragment extends Fragment {

	private static int logoID[] = { R.drawable.logo1, R.drawable.logo2,
			R.drawable.logo3, R.drawable.logo4, R.drawable.logo5,
			R.drawable.logo6, R.drawable.logo7, R.drawable.logo8,
			R.drawable.logo9, };

	public static TopDealsFragment newInstance(int store) {

		TopDealsFragment fragment = new TopDealsFragment();
		Bundle bundle = new Bundle();
		String query = GameDealQueries.getTopDeals(store);
		bundle.putString("query", query);
		bundle.putInt("storeIndex", store);
		fragment.setArguments(bundle);

		return fragment;
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.e("CS Mobile", getArguments().getString("query"));
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (CSMobileApplication.getStoreReady(getArguments().getInt(
				"storeIndex"))) {

			View view = inflater.inflate(R.layout.fragment_top_deals,
					container, false);
			// setContentView(R.layout.activity_top_deals);
			ImageView header = (ImageView) view.findViewById(R.id.header);
			Bitmap logo = BitmapFactory.decodeResource(getResources(),
					logoID[getArguments().getInt("storeIndex")]);
			header.setImageBitmap(logo);
			ListView dealsList = (ListView) view.findViewById(R.id.deals);
			CSMobileApplication state = (CSMobileApplication) getActivity()
					.getApplicationContext();
			int storeID = getArguments().getInt("storeIndex");
			for (int x = 0; x < state.getDeals(storeID).length; x++) {
				if (state.getDeals(storeID)[x] == null) {
					System.out.println("TopDealsFragment Deals:  null");
				} else {
					System.out.println("TopDealsFragment Deals:  "
							+ state.getDeals(storeID)[x].getTitle());
				}
			}

			GameDealAdapter dealAdapter = new GameDealAdapter(getActivity(),
					R.layout.game_deal_view, state.getDeals(storeID));
			dealsList.setAdapter(dealAdapter);
			return view;
		} else {
			View v = inflater.inflate(R.layout.fragment_top_deals_loading,
					container, false);
			ImageView header = (ImageView) v.findViewById(R.id.header);
			Bitmap logo = BitmapFactory.decodeResource(getResources(),
					logoID[getArguments().getInt("storeIndex")]);
			header.setImageBitmap(logo);
			return v;
		}
	}
}
